package com.guli.edu.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.guli.edu.client.UcenterClient;
import com.guli.edu.entity.Comment;
import com.guli.edu.service.CommentService;
import com.guli.utils.JwtUtils;
import com.guli.utils.R;
import com.guli.utils.UcenterMember;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 评论 前端控制器
 * </p>
 *
 * @author ZhaoZhenyu
 * @since 2022-10-03
 */

//@CrossOrigin
@RestController
@RequestMapping("/edu/comment")
public class CommentController {

    @Autowired
    private CommentService commentService;

    @Autowired
    private UcenterClient ucenterClient;

    @GetMapping("commentByPage/{page}/{limit}")
    public R commentByPage(
            @PathVariable Long page, @PathVariable Long limit,String courseId) {

        Page<Comment> pageParam = new Page<>(page, limit);
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("course_id",courseId);
        commentService.page(pageParam, wrapper);

        Map<String, Object> map = new HashMap<>();
        map.put("items", pageParam.getRecords());
        map.put("current", pageParam.getCurrent());
        map.put("pages", pageParam.getPages());
        map.put("size", pageParam.getSize());
        map.put("total", pageParam.getTotal());
        map.put("hasNext", pageParam.hasNext());
        map.put("hasPrevious", pageParam.hasPrevious());

        return R.ok().data(map);
    }

    @PostMapping("auth/saveComment")
    public R saveComment(@RequestBody Comment comment, HttpServletRequest request) {

        // 前端请求头里面有token 解析token
        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        // 没有token就重新登录
        if(StringUtils.isEmpty(memberId)) {
            return R.error().code(28004).message("请登录");
        }
        comment.setMemberId(memberId);

        // 远程调用ucenter
        UcenterMember ucenterInfo = ucenterClient.getInfo(memberId);

        comment.setNickname(ucenterInfo.getNickname());
        comment.setAvatar(ucenterInfo.getAvatar());

        commentService.save(comment);
        return R.ok();
    }

}

